import {getUserInfo , removeToken} from "../../utils/api/user"

const user = {
    state:{
        username : "",
        userId : "",
        roleCode : "",
        permissions : [],
    },
    mutations:{
        SET_USER : (state,userInfo)  => {
            state.username = userInfo.userName,
            state.userId = userInfo.uid,
            state.roleCode = userInfo.userRole.roleName
            // state.permissions = userInfo.permissions
        },
        RESET_USER : (state) =>{
            state.username = "",
            state.userId = "",
            state.roleCodes = "",
            state.permissions = ""
        },
        SET_ROLES: (state, roleCodes) => {
            state.roleCodes = roleCodes
        }
    },
    actions:{
        GetUserInfo({commit,state}){
            return new Promise((resolve,rejects) => {
                var token = sessionStorage.getItem('access_token');
                getUserInfo(token).then(response => {

                    if (!response.data.rows &&!response.data.rows.length) {
                        rejects('error 500')
                    }

                    const data = response.data.rows[0];
                    commit('SET_USER',data);
                    resolve(data);
                }).catch(error =>{
                    rejects(error)
                });
            })
        },

        LogOut({commit}) {
            return new Promise((resolve, reject) => {
                commit('RESET_USER', '')
                removeToken()
                resolve()
            })
          },

    }
}

export default user